import { useEffect, useState } from "react";
import { Button, Spin, Tooltip, Input, message } from "antd";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { getUserAllTag, getUserStageTag } from "@/assets/js/networkRequest/method";

interface TagSelecteProps {
  customerTag: any;
  setVisible: any;
  setCustomerTag: any;
}

let allTag: any = [];
let stageTag: any = [];

const TagSelecte = ({ customerTag, setVisible, setCustomerTag }: TagSelecteProps) => {
  const [loading, setLoading] = useState(true);
  const [, setRender] = useState(0);

  useEffect(() => {
    (async () => {
      let allTagData: any = await getUserAllTag();
      let stageTagData: any = await getUserStageTag();
      if (allTagData.status_code === 200 && stageTagData.status_code === 200) {
        allTag = allTagData.tag_group_list.map((item: any) => {
          item.selected = false;
          return item;
        });
        stageTag = stageTagData.stage_list.map((item: any) => {
          item.selected = false;
          return item;
        });
      }
      initSelectedTag();
      setLoading(false);
    })();
  }, []);

  useEffect(() => {
    initSelectedTag();
  }, [customerTag]);

  // 初始化选择的标签
  const initSelectedTag = () => {
    if (!customerTag.length) {
      return;
    }
    stageTag.map((item: any) => {
      item.selected = false;
      customerTag.map((selectItem: any) => {
        if (item.id === selectItem.id) {
          item.selected = true;
        }
      });
    });
    allTag.map((item: any) => {
      item.tag_list.map((tagItem: any) => {
        tagItem.selected = false;
        // eslint-disable-next-line max-nested-callbacks
        customerTag.map((selectItem: any) => {
          if (tagItem.id === selectItem.id) {
            tagItem.selected = true;
          }
        });
      });
    });
    setRender(Math.random() + 1);
  };

  // 点击标签
  const clickTag = ({ typeIndex, tagIndex }: { typeIndex: number; tagIndex: number }) => {
    // console.log(typeIndex, tagIndex);

    if (typeIndex === -1) {
      stageTag[tagIndex].selected = !stageTag[tagIndex].selected;
    } else {
      allTag[typeIndex].tag_list[tagIndex].selected = !allTag[typeIndex].tag_list[
        tagIndex
      ].selected;
    }
    setRender(Math.random() + 1);
  };

  // 添加标签
  const showInput = ({
    typeIndex,
    flag,
    value,
  }: {
    typeIndex: number;
    flag: boolean;
    value?: string;
  }) => {
    allTag[typeIndex].isInput = flag;
    if (value && allTag[typeIndex].tag_list.some((item: any) => item.name === value)) {
      message.warn("标签不能重复");
    }
    setRender(Math.random() + 1);
  };

  // 保存选择的标签
  const saveTag = () => {
    // 阶段标签
    let stageTagId = stageTag.filter((item: any) => item.selected);
    // // 类型标签
    let allTagId = allTag
      .map((item: any) => item.tag_list)
      .reduce((a: any, b: any) => a.concat(b))
      .filter((item: any) => item.selected);
    setCustomerTag([...stageTagId, ...allTagId]);
  };

  return (
    <>
      <h2 className="dialog-title">选择标签</h2>
      <section className="h-530 scrollY overflow-auto pr-26 leading-5">
        <Spin spinning={loading}>
          {/* 阶段标签 */}
          <div className="border-b-1 border-dashed border-grey-200 pb-8 mb-16">
            <p className="flex items-center text-xs leading-5 text-grey-400 whitespace-nowrap mb-5">
              客户阶段：
              <Tooltip
                placement="topLeft"
                title={
                  <p className="text-xs text-grey-600 leading-6 px-6 py-4">
                    可通过选择阶段标签，自动给客户设置客户阶段哦～
                    <a
                      target="_blank"
                      href="https://shimo.im/docs/aBAYV4gebbI18N3j/read"
                      className="text-blue-default">
                      查看介绍
                    </a>
                  </p>
                }
                color="#fff">
                <QuestionCircleOutlined />
              </Tooltip>
            </p>
            <ul className="flex items-baseline flex-wrap">
              {stageTag.map((item: any, index: number) => {
                return (
                  <li
                    className={`mb-10 px-14 py-5 rounded-sm h-28 mr-10 cursor-pointer select-none border-1 border-solid ${
                      item.selected
                        ? "text-blue-default bg-grey-e7f7ff border-blue-default"
                        : "text-grey-600 bg-grey-100 border-grey-300"
                    }`}
                    key={item.id}
                    onClick={() => {
                      clickTag({ typeIndex: -1, tagIndex: index });
                    }}>
                    {item.stage_name}
                  </li>
                );
              })}
            </ul>
          </div>

          {/* 类型标签 */}
          {allTag.map((item: any, index: number) => {
            return (
              <div className="mb-2" key={item.name}>
                <p className="flex items-center text-xs leading-5 text-grey-400 whitespace-nowrap mb-5">
                  {item.name}:
                </p>
                <div className="flex items-baseline flex-wrap">
                  <Button
                    className="h-28 mr-10 px-8 rounded-sm text-grey-600"
                    size="small"
                    icon={<i className="iconfont icon-tianjia1"></i>}
                    onClick={() => {
                      showInput({ typeIndex: index, flag: true });
                    }}>
                    添加
                  </Button>
                  {item.isInput ? (
                    <div className="w-106 h-28 text-grey-800 rounded-sm mr-10 mb-5 border-1 border-solid border-grey-300">
                      <Input
                        placeholder="输入后回车"
                        bordered={false}
                        autoFocus
                        onBlur={(e: any) => {
                          let value = e.target.value;
                          showInput({ typeIndex: index, flag: false, value });
                        }}
                        onPressEnter={(e: any) => {
                          let value = e.target.value;
                          showInput({ typeIndex: index, flag: false, value });
                        }}
                      />
                    </div>
                  ) : null}
                  {item.tag_list.map((tagItem: any, tagIndex: number) => {
                    return (
                      <li
                        className={`mb-10 px-14 py-5 rounded-sm h-28 mr-10 cursor-pointer select-none  border-1 border-solid ${
                          tagItem.selected
                            ? "text-blue-default bg-grey-e7f7ff border-blue-default"
                            : "text-grey-600 bg-grey-100 border-grey-300"
                        }`}
                        key={tagItem.id}
                        onClick={() => {
                          clickTag({ typeIndex: index, tagIndex: tagIndex });
                        }}>
                        {tagItem.name}
                      </li>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </Spin>
      </section>

      {/* 底部操作 */}
      <div className="btn-wrap">
        <div className="left">
          <i className="iconfont icon-tianjia1"></i>
          <span className="text">新建标签组</span>
        </div>

        <div className="right">
          <Button
            onClick={() => {
              setVisible(false);
            }}>
            取消
          </Button>
          <Button
            type="primary"
            onClick={() => {
              saveTag();
              setVisible(false);
            }}>
            保存
          </Button>
        </div>
      </div>
    </>
  );
};

export default TagSelecte;
